package com.anxin.act.busFlow.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anxin.act.busFlow.dao.WfBusRoundDao;
import com.anxin.act.busFlow.dao.WfConfigFlowDao;
import com.anxin.act.busFlow.dao.WfConfigNodeDao;
import com.anxin.act.busFlow.entity.*;
import com.anxin.common.utils.ListUtils;
import com.anxin.common.utils.StringUtils;
import com.anxin.common.utils.sys.RoleUtils;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.framework.web.service.BaseService;
import com.anxin.common.utils.SecurityUtils;
import com.anxin.sys.message.service.MsgBaseService;
import com.anxin.sys.message.service.SendAppService;
import com.anxin.sys.message.service.SendEmailService;
import com.anxin.sys.monitor.interfaces.JobInvoke;
import com.anxin.sys.system.entity.SysUser;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.anxin.act.busFlow.dao.WfBusNodeEvolveDao;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务节点进展Service业务层处理
 *
 * @author jbs
 * @date 2020-04-16
 */
@Service
public class WfBusNodeEvolveService extends BaseService<WfBusNodeEvolveDao,WfBusNodeEvolve> implements JobInvoke {
    @Autowired
    private WfBusNodeEvolveDao wfBusNodeEvolveDao;
    @Autowired
    private WfBusRoundDao wfBusRoundDao;
    @Autowired
    private WfConfigNodeDao wfConfigNodeDao;
    @Autowired
    private WfConfigFlowDao wfConfigFlowDao;
    @Autowired
    private MsgBaseService msgBaseService;
    @Autowired
    private SendEmailService sendEmailService;
    @Autowired
    private SendAppService sendAppService;



    /**
     * 查询业务节点进展
     *
     * @param id 业务节点进展ID
     * @return 业务节点进展
     */
    public WfBusNodeEvolve getById(String id){
        return wfBusNodeEvolveDao.getById(id);
    }

    /**
     * 查询业务节点进展列表
     *
     * @param wfBusNodeEvolve 业务节点进展
     * @return 业务节点进展
     */
    public List<WfBusNodeEvolve> findList(WfBusNodeEvolve wfBusNodeEvolve){
        return wfBusNodeEvolveDao.findList(wfBusNodeEvolve);
    }

    /**
     * 根据业务ID获取业务节点名称
     * @param busId 业务ID
     * @return 业务节点名称
     */
    public String getNodeNameByBusId(String busId){
        return wfBusNodeEvolveDao.getNodeNameByBusId(busId);
    }

    /**
     * 保存数据
     * @param busId 业务ID
     * @param busType 业务类型
     * @param nodeId 节点ID
     */
    public void save(String busId,String busType,String nodeId,String roundId){
        WfBusNode wfBusNode = new WfBusNode();
        wfBusNode.setBusId(busId);
        wfBusNode.setBusType(busType);
        wfBusNode.setNodeId(nodeId);
        this.saveByBusNode(wfBusNode,roundId);

    }


    /**
     * 根据业务状态初始化业务当前节点
     * @param wfConfigNodeList
     * @param busStatus
     * @param busId
     * @param busType
     */
    public void initByBusNode(List<WfConfigNode> wfConfigNodeList,String busStatus,String busId,String busType){
        WfBusNodeEvolve wfBusNodeEvolve = new WfBusNodeEvolve();
        wfBusNodeEvolve.setBusId(busId);
        wfBusNodeEvolve.setBusType(busType);
        List<WfBusNodeEvolve> evolveList = this.findList(wfBusNodeEvolve);
        // 如果已经存在则不初始化了
        if (evolveList.size() > 0){
            return;
        }

        WfConfigNode wfConfigNode = wfConfigNodeList.get(0);
        for (WfConfigNode configNode : wfConfigNodeList) {
            if ( configNode.getBusStatus() != null && configNode.getBusStatus().equals(busStatus)){
                wfConfigNode = configNode;
                break;
            }
        }


        wfBusNodeEvolve.setNodeId(wfConfigNode.getId());
        wfBusNodeEvolve.setLatest("Y");
        // 当前时间
        wfBusNodeEvolve.setEvolveTime(new Date(System.currentTimeMillis()));
        this.save(wfBusNodeEvolve);

    }


    /**
     * 根据bus保存记录
     * @param wfBusNode
     */
    @Transactional(readOnly = false)
    public void saveByBusNode(WfBusNode wfBusNode,String roundId){
        WfBusNodeEvolve wfBusNodeEvolve = new WfBusNodeEvolve();
        wfBusNodeEvolve.setBusId(wfBusNode.getBusId());
        wfBusNodeEvolve.setBusType(wfBusNode.getBusType());
        wfBusNodeEvolve.setNodeId(wfBusNode.getNodeId());
        wfBusNodeEvolve.setRoundId(roundId);
        if (StringUtils.isNotBlank(wfBusNode.getRoundId())){
            wfBusNodeEvolve.setRoundId(wfBusNode.getRoundId());
        }
        wfBusNodeEvolve.setLatest("Y");

        // 查询当前节点是否存在
        List<WfBusNodeEvolve> evolveList = this.findList(wfBusNodeEvolve);
        // 之前不存在才创建
        if (evolveList.size() == 0){
            // 将之前的节点都设置为不是最新
            wfBusNodeEvolveDao.updateNoLatest(wfBusNodeEvolve);

            // 更新历史进展的离开时间和滞留时间
            wfBusNodeEvolveDao.updateEvolveTime(wfBusNodeEvolve);

            String latest = "Y";
            if (StringUtils.isNotBlank(roundId)){
                WfBusRound wfBusRound = wfBusRoundDao.getById(roundId);
                if (wfBusRound != null && wfBusRound.getNum() != 1){
                    latest = "W";
                }
            }
            // 保存新节点
            wfBusNodeEvolve.setLatest(latest);
            // 轮次ID
            wfBusNodeEvolve.setRoundId(roundId);

            // 当前时间
            wfBusNodeEvolve.setEvolveTime(new Date(System.currentTimeMillis()));
            this.save(wfBusNodeEvolve);
        }
    }


    /**
     * 保存业务节点进展
     *
     * @param wfBusNodeEvolve 业务节点进展
     * @return 结果
     */
    public int update(WfBusNodeEvolve wfBusNodeEvolve){
        return super.save(wfBusNodeEvolve);
    }


    /**
     * 删除业务节点进展信息
     *
     * @param id 业务节点进展ID
     * @return 结果
     */
    public int deleteById(String id){
        SysUser user = SecurityUtils.getUser();
        return wfBusNodeEvolveDao.deleteById(id,user.getId());
    }

    /**
     * 查询当前一级节点
     * @param busType
     * @param busId
     */
    public WfBusNodeEvolve getLatestEvolve(String busType,String busId,String roundId){
        return dao.getLatestEvolve(busType,busId,roundId);
    }


    /**
     * 获取最新节点
     *
     * @param busId
     */
    public WfBusNodeEvolve getLastNodeByBusId(String busId){
        return dao.getLastNodeByBusId(busId);
    }

    /**
     * 获取提醒用户
     * @param wfConfigNode
     * @return
     */
    private List<String> getReminderUserByNode(WfConfigNode wfConfigNode){
        List<String> resUser = new ArrayList<>();

        // 提醒的角色
        if (wfConfigNode.getOtherReminderRoles() != null){
            String otherReminderRoles = wfConfigNode.getOtherReminderRoles();
            resUser = UserUtils.getUserIdByRoleId(otherReminderRoles);
        }

        // 提醒的用户
        if (wfConfigNode.getOtherReminderUser() != null){
            for (int i = 0; i < wfConfigNode.getOtherReminderUser().size(); i++) {
                String userId = wfConfigNode.getOtherReminderUser().getString(i);

                ListUtils.addEliminateRepetitive(resUser,userId);
            }
        }

        return resUser;
    }

    /**
     * 替换字符串
     * @param content
     * @param dealName
     * @return
     */
    private String alternativeContent(String content,String dealName){


        return content;
    }

    /**
     * 获取通知数据
     * @param dealName
     * @return
     */
    private JSONObject getReminderData(String dealName){
        JSONObject resData = new JSONObject();
        resData.put("dealName",dealName);
        return resData;
    }


    /**
     * 发送
     * @param dealId
     * @param dealName
     * @param wfConfigNode
     */
    private void sendReminderByDeal(String dealId,String dealName,WfConfigNode wfConfigNode,List<String> reminderUserList){
        // 是否通知团队成员
        if ("Y".equals(wfConfigNode.getIsReminderTeamMembers())) {
            List<String> dealTeamUserIdList = wfBusNodeEvolveDao.findDealTeam(dealId);
            for (String userId : dealTeamUserIdList) {
                ListUtils.addEliminateRepetitive(reminderUserList,userId);
            }
        }

        if (reminderUserList.size() > 0){
            JSONObject reminderData = this.getReminderData(dealName);
            String title = StringUtils.format(wfConfigNode.getReminderTitle(),reminderData);
            String content = StringUtils.format(wfConfigNode.getReminderContent(),reminderData);

            // 发送提醒
            JSONArray reminderMode = wfConfigNode.getReminderMode();
            for (int i = 0; i < reminderMode.size(); i++) {
                String mode = reminderMode.getString(i);
                switch (mode){
                    // 系统通知
                    case "XTTX":
                        msgBaseService.sendMessage(title,content,null,null,reminderUserList);
                        break;
                    //邮件
                    case "EMAIL":
                        sendEmailService.sendEmail(reminderUserList,title,content);
                        break;
                    // APP
                    case "APP":
                        sendAppService.push(title,content,reminderUserList);
                        break;
                    default:
                }
            }
        }

    }


    /**
     * 发送提醒
     */
    public void sendReminder(){
        List<WfConfigNode> reminderNodeList = wfConfigNodeDao.findReminderNode();
        for (WfConfigNode wfConfigNode : reminderNodeList) {

            List<String> reminderUserList = this.getReminderUserByNode(wfConfigNode);

            WfConfigFlow wfConfigFlow = wfConfigFlowDao.getById(wfConfigNode.getFlowId());
            if ("deal".equals(wfConfigFlow.getBusType())){
                JSONArray reminderFrequency = wfConfigNode.getReminderFrequency();
                for (int i = 0; i < reminderFrequency.size(); i++) {
                    String residenceTime = reminderFrequency.getString(0);
                    List<Map<String, String>> dealList = wfBusNodeEvolveDao.findDealByResidenceTime(StringUtils.symbolHandler(wfConfigNode.getId()), residenceTime);
                    for (Map<String, String> dealMap : dealList) {
                        this.sendReminderByDeal(dealMap.get("id"),dealMap.get("dealName"),wfConfigNode,reminderUserList);
                    }
                }
            }
        }
    }

}
